package com.itheima.htmo_01.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.htmo_01.dto.RegisterUserDTO;
import com.itheima.htmo_01.exception.BusinessException;
import com.itheima.htmo_01.mapper.UserMapper;
import com.itheima.htmo_01.pojo.User;
import com.itheima.htmo_01.service.UserService;
import com.itheima.htmo_01.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {




    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByUserName(String username){

        return getOne(new LambdaQueryWrapper<User>().eq(User::getUsername,username));


//        User u=userMapper.findByUsername(username);
//        return u;
    }

    @Override
    public void register(RegisterUserDTO registerUserDTO){
// 加密
        String md5String= Md5Util.getMD5String(registerUserDTO.getPassword());

        User user = BeanUtil.toBean(registerUserDTO, User.class);

        // 设置加密后的密码
        user.setPassword(md5String);

        // 初始化创建时间和修改时间
        user.setUpdateTime(LocalDateTime.now());
        user.setCreateTime(LocalDateTime.now());

        save(user);

// 添加
//        userMapper.add(username,md5String);
    }

    @Override
    public void update(User user) {

        User queryUser = getById(user.getId());
        if(ObjectUtil.isEmpty(queryUser)){
            throw new BusinessException(500,"用户不存在");
        }


        BeanUtil.copyProperties(queryUser,user);



        queryUser.setUpdateTime(LocalDateTime.now());
//        userMapper.update(user);

        updateById(user);

    }
}
